# -*- coding: utf-8 -*-
# standard
import os
import sys
from datetime import datetime
from typing import Union

# third
import influxdb_client  # pip install influxdb-client  https://influxdb-client.readthedocs.io/en/latest/
from influxdb_client.client.influxdb_client_async import InfluxDBClientAsync
from influxdb_client.client import flux_table
from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS, ASYNCHRONOUS, WriteOptions
from influxdb_client.client.write_api_async import WriteApiAsync

# local
_P_PATH =  os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)


"""
@Title:   
@File: influxdb_model.py
@Author: walle 2024年11日13日 16时48分41秒
@Version: 1.0.0
@Desc: 
"""


# 注意，查询测试的结果是，API 比直接调用客户端查询要慢。多了接近100毫秒的时间
# 但是，API 的好处是支持的功能非常丰富， 比如设置警告，通知灯，远比 客户端要强大的多，
# 查询数据的 API 文档地址 https://docs.influxdata.com/influxdb/v2/api/#operation/PostQuery
# 使用API查询数据的指南 https://docs.influxdata.com/influxdb/v2/query-data/execute-queries/influx-api/


INFLUXDB_TOKEN = "pazwlwOpZpsuxysK7Q53e_bh_NurkA9YyOVWD9Vl4ApA4SnD-dQGQdHpITLO3Sqh7BJnOgJ4YS0EMYqVEAvR2w=="
INFLUXDB_ORG = "yhjk"
ORG_ID = "d63fb57688f45933"  # 在管理页面，About页面可以找到
INFLUXDB_URL = "http://iot.ihcc.com.cn:8086"
INFLUX_CLI = influxdb_client.InfluxDBClient(url=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG)
INFLUX_CLI_ASYNC: InfluxDBClientAsync = None
API_HEADER = headers = {
        "Authorization": f"Token {INFLUXDB_TOKEN}",
        "Accept": "application/csv",
        "Content-type": "application/vnd.flux"
    }


async def get_influxdb_cli_async() -> InfluxDBClientAsync:
    """
    获取influxdb客户端
    注意：InfluxDBClientAsync的构造器必须在 async 函数下运行
    :return: _description_
    """
    global INFLUX_CLI_ASYNC
    if INFLUX_CLI_ASYNC is None:
        INFLUX_CLI_ASYNC = InfluxDBClientAsync(url=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG)
    return INFLUX_CLI_ASYNC



def convert_to_local_time(influx_time: datetime, to_plain: bool = True) -> Union[datetime, str]:
    """
    将influxdb时间转换为本地时间
    :param influx_time: _description_
    :param to_plain: _description_, defaults to True
    :return: _description_
    """
    local_time = datetime.fromtimestamp(influx_time.timestamp())
    if to_plain:
        local_time = local_time.strftime("%Y-%m-%d %H:%M:%S")
    return local_time



if __name__ == '__main__':
    pass